import BasePlugin from './BasePlugin';

/**
 * 导出插件 - 处理画布导出功能
 */
export default class ExportPlugin extends BasePlugin {
    constructor() {
        super();
        this.defaultOptions = {
            format: 'png',
            quality: 1,
            multiplier: 1,
            enableRetinaScaling: true,
            withoutTransparency: false,
            name: 'canvas'
        };
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
    }

    /**
     * 导出为图片
     */
    exportToImage(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        const exportOptions = {
            ...this.defaultOptions,
            ...options
        };

        // 保存当前画布状态
        const originalViewport = this.canvas.viewportTransform.slice();
        const originalZoom = this.canvas.getZoom();
        const originalWidth = this.canvas.width;
        const originalHeight = this.canvas.height;

        // 如果指定了尺寸，临时调整画布大小
        if (exportOptions.width || exportOptions.height) {
            this.canvas.setWidth(exportOptions.width || originalWidth);
            this.canvas.setHeight(exportOptions.height || originalHeight);
            this.canvas.setZoom(1);
        }

        // 准备导出选项
        const dataUrlOptions = {
            format: exportOptions.format,
            quality: exportOptions.quality,
            multiplier: exportOptions.multiplier,
            enableRetinaScaling: exportOptions.enableRetinaScaling,
            withoutTransparency: exportOptions.withoutTransparency
        };

        // 如果指定了裁剪区域
        if (exportOptions.crop) {
            dataUrlOptions.left = exportOptions.crop.left;
            dataUrlOptions.top = exportOptions.crop.top;
            dataUrlOptions.width = exportOptions.crop.width;
            dataUrlOptions.height = exportOptions.crop.height;
        }

        // 导出画布为 DataURL
        const dataUrl = this.canvas.toDataURL(dataUrlOptions);

        // 恢复画布状态
        if (exportOptions.width || exportOptions.height) {
            this.canvas.setWidth(originalWidth);
            this.canvas.setHeight(originalHeight);
            this.canvas.setZoom(originalZoom);
            this.canvas.viewportTransform = originalViewport;
            this.canvas.renderAll();
        }

        // 触发导出事件
        this._emitExportEvent('image', {
            dataUrl,
            options: exportOptions
        });

        // 如果需要下载
        if (exportOptions.download) {
            this._downloadFile(
                dataUrl,
                `${exportOptions.name}.${exportOptions.format}`
            );
        }

        return dataUrl;
    }

    /**
     * 导出为 JSON
     */
    exportToJSON(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        const json = this.canvas.toJSON([
            'name',
            'id',
            'customProperty',
            ...options.additionalFields || []
        ]);

        // 触发导出事件
        this._emitExportEvent('json', {
            json,
            options
        });

        // 如果需要下载
        if (options.download) {
            const jsonString = JSON.stringify(json, null, 2);
            const dataUrl = 'data:text/json;charset=utf-8,' + encodeURIComponent(jsonString);
            this._downloadFile(dataUrl, `${options.name || 'canvas'}.json`);
        }

        return json;
    }

    /**
     * 导出为 SVG
     */
    exportToSVG(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        const svg = this.canvas.toSVG({
            viewBox: options.viewBox,
            width: options.width,
            height: options.height,
            encoding: 'UTF-8',
            ...options
        });

        // 触发导出事件
        this._emitExportEvent('svg', {
            svg,
            options
        });

        // 如果需要下载
        if (options.download) {
            const dataUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
            this._downloadFile(dataUrl, `${options.name || 'canvas'}.svg`);
        }

        return svg;
    }

    /**
     * 导出选中对象
     */
    exportSelection(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (!activeObject) return;

        // 创建临时画布
        const tempCanvas = new fabric.Canvas(null, {
            width: activeObject.width * activeObject.scaleX,
            height: activeObject.height * activeObject.scaleY
        });

        // 克隆选中对象
        activeObject.clone((clonedObj) => {
            // 重置对象位置
            clonedObj.set({
                left: tempCanvas.width / 2,
                top: tempCanvas.height / 2,
                originX: 'center',
                originY: 'center'
            });

            // 添加到临时画布
            tempCanvas.add(clonedObj);
            tempCanvas.centerObject(clonedObj);

            // 导出临时画布
            const dataUrl = tempCanvas.toDataURL({
                format: options.format || 'png',
                quality: options.quality || 1,
                multiplier: options.multiplier || 1
            });

            // 触发导出事件
            this._emitExportEvent('selection', {
                dataUrl,
                options
            });

            // 如果需要下载
            if (options.download) {
                this._downloadFile(
                    dataUrl,
                    `${options.name || 'selection'}.${options.format || 'png'}`
                );
            }

            // 销毁临时画布
            tempCanvas.dispose();
        });
    }

    /**
     * 导出为打印格式
     */
    exportToPrint(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        // 创建打印窗口
        const printWindow = window.open('', '_blank');
        if (!printWindow) return;

        // 获取画布数据
        const dataUrl = this.canvas.toDataURL({
            format: 'png',
            quality: 1,
            multiplier: options.multiplier || 2
        });

        // 创建打印页面 HTML
        const html = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>${options.title || 'Print Canvas'}</title>
                <style>
                    body {
                        margin: 0;
                        padding: 20px;
                        text-align: center;
                    }
                    img {
                        max-width: 100%;
                        height: auto;
                    }
                    @media print {
                        @page {
                            size: auto;
                            margin: 0;
                        }
                        body {
                            padding: 0;
                        }
                    }
                </style>
            </head>
            <body>
                <img src="${dataUrl}" />
                <script>
                    window.onload = function() {
                        setTimeout(function() {
                            window.print();
                            window.close();
                        }, 250);
                    };
                </script>
            </body>
            </html>
        `;

        // 写入打印页面内容
        printWindow.document.write(html);
        printWindow.document.close();

        // 触发导出事件
        this._emitExportEvent('print', {
            dataUrl,
            options
        });
    }

    /**
     * 下载文件
     */
    _downloadFile(dataUrl, filename) {
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    /**
     * 发送导出事件
     */
    _emitExportEvent(type, data = null) {
        this.editor.emit('export:' + type, {
            type,
            data
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        super.destroy();
    }
} 